<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片上传测试</title>
    <style>
        .upload-container {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 8px;
            text-align: center;
        }
        .upload-area {
            padding: 40px;
            cursor: pointer;
        }
        .upload-area:hover {
            background-color: #f5f5f5;
        }
        .preview-container {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .preview-item {
            position: relative;
            width: 150px;
            height: 150px;
        }
        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
        }
        .preview-item .remove-btn {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .upload-btn {
            margin-top: 20px;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .upload-btn:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <div class="upload-container">
        <div class="upload-area" id="dropZone">
            <h3>点击或拖拽图片到此处上传</h3>
            <p>支持 jpg、png、gif 格式，单个文件不超过 5MB</p>
            <input type="file" id="fileInput" multiple accept="image/*" style="display: none;">
        </div>
        <div class="preview-container" id="previewContainer"></div>
        <button class="upload-btn" id="uploadBtn">开始上传</button>
    </div>

    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const previewContainer = document.getElementById('previewContainer');
        const uploadBtn = document.getElementById('uploadBtn');
        let files = [];

        // 点击上传区域触发文件选择
        dropZone.addEventListener('click', () => {
            fileInput.click();
        });

        // 处理文件选择
        fileInput.addEventListener('change', handleFiles);

        // 处理拖拽
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.style.backgroundColor = '#f0f0f0';
        });

        dropZone.addEventListener('dragleave', (e) => {
            e.preventDefault();
            dropZone.style.backgroundColor = '';
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.style.backgroundColor = '';
            handleFiles({ target: { files: e.dataTransfer.files } });
        });

        // 处理文件
        function handleFiles(e) {
            const newFiles = Array.from(e.target.files);
            
            // 验证文件
            newFiles.forEach(file => {
                if (!file.type.startsWith('image/')) {
                    alert('请只上传图片文件！');
                    return;
                }
                if (file.size > 5 * 1024 * 1024) {
                    alert('文件大小不能超过 5MB！');
                    return;
                }
                // 只保留最新选择的文件
                files = [file];
                updatePreview();
            });
        }

        // 创建预览
        function createPreview(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const div = document.createElement('div');
                div.className = 'preview-item';
                div.innerHTML = `
                    <img src="${e.target.result}" alt="预览图">
                    <button class="remove-btn" onclick="removeFile('${file.name}')">×</button>
                `;
                previewContainer.appendChild(div);
            };
            reader.readAsDataURL(file);
        }

        // 移除文件
        function removeFile(fileName) {
            files = files.filter(file => file.name !== fileName);
            updatePreview();
        }

        // 更新预览
        function updatePreview() {
            previewContainer.innerHTML = '';
            files.forEach(file => createPreview(file));
        }

        // 上传按钮点击事件
        uploadBtn.addEventListener('click', () => {
            if (files.length === 0) {
                alert('请先选择要上传的图片！');
                return;
            }
            
            // 这里添加实际的上传逻辑
            const formData = new FormData();
            formData.append('image', files[0]);  // 修改参数名为 'image'，匹配后端 @RequestParam("image")

            // 更新为实际的上传接口
            fetch('http://localhost:8080/files/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('服务器错误：' + response.status);
                }
                return response.text();  // 改用 text() 而不是 json()
            })
            .then(data => {
                alert('上传成功！文件路径：' + data);
                files = [];
                updatePreview();
            })
            .catch(error => {
                console.error('上传错误：', error);
                alert('上传失败：' + error.message + '\n请确保服务器正常运行且已正确配置 FileUtils 服务。');
            });
        });
    </script>
</body>
</html>
